package com.miya.demo.config;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.miya.demo.common.constant.PersistenceConstants;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;


/**
 * mybatis +配置
 *
 * @author Caixiaowei
 * @date 2021/09/22
 */
@Configuration
public class MybatisPlusConfig {

    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            /**
             * 插入填充
             *
             * @param metaObject 元对象
             */
            @Override
            public void insertFill(MetaObject metaObject) {
                this.strictInsertFill(metaObject, PersistenceConstants.PROPERTY_CREATE_TIME, () -> LocalDateTime.now(), LocalDateTime.class);
                this.strictInsertFill(metaObject, PersistenceConstants.PROPERTY_UPDATE_TIME, () -> LocalDateTime.now(), LocalDateTime.class);
                Long loginId = StpUtil.getLoginIdAsLong();
                if (StpUtil.isLogin() && loginId != null) {
                    this.strictInsertFill(metaObject, PersistenceConstants.PROPERTY_CREATE_BY, () -> loginId, Long.class);
                    this.strictInsertFill(metaObject, PersistenceConstants.PROPERTY_UPDATE_BY, () -> loginId, Long.class);
                }
            }

            /**
             * 更新填充
             *
             * @param metaObject 元对象
             */
            @Override
            public void updateFill(MetaObject metaObject) {
                this.strictUpdateFill(metaObject, PersistenceConstants.PROPERTY_UPDATE_TIME, () -> LocalDateTime.now(), LocalDateTime.class);
                Long loginId = StpUtil.getLoginIdAsLong();
                if (StpUtil.isLogin() && loginId != null) {
                    this.strictInsertFill(metaObject, PersistenceConstants.PROPERTY_UPDATE_BY, () -> loginId, Long.class);
                }
            }
        };
    }
}
